package cn.sumpu.app.coolsk.biz.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

//import org.springframework.transaction.annotation.Transactional;

import cn.sumpu.app.coolsk.biz.TicketBiz;
import cn.sumpu.app.coolsk.constant.Table;
import cn.sumpu.app.coolsk.dao.TicketDao;
import cn.sumpu.app.coolsk.domain.Ticket;
import cn.sumpu.app.coolsk.domain.TicketPrice;
import cn.sumpu.app.coolsk.exception.AppBusinessException;
import cn.sumpu.toolkit.common.page.PageModel;
import cn.sumpu.toolkit.common.util.Common;
import cn.sumpu.toolkit.common.util.Encode;

public class TicketBizImpl implements TicketBiz {

    private Calendar                     cal = Calendar.getInstance();
    private TicketDao                    ticketDao;

    private DataSourceTransactionManager transactionManager;
    @Autowired
    private IdentifierBizImpl            identifierBiz;

    public void setTicketDao(TicketDao ticketDao) {
        this.ticketDao = ticketDao;
    }

    public void setTransactionManager(DataSourceTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public PageModel getScenicTicket(Integer page, Integer pagesize, String name, String scId) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        int size = pagesize;
        map.put("startId", (page - 1) * size);
        map.put("pageSize", size);
        map.put("scenic", scId);
        if (!Common.empty(name)) {
            map.put("name", "%" + name + "%");
        }
        int count = ticketDao.getTicketCount(map);
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(ticketDao.getTicket(map));
        pm.setPageSize(size);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + size - 1) / size);
        return pm;
    }

    @Override
    public Ticket saveTicket(Ticket ticket) throws AppBusinessException {
        if (ticket != null) {
            if (Common.empty(ticket.getId())) {
                ticket.setId(identifierBiz.generateId(Table.TICKET));
                ticketDao.insertTicket(ticket);
            } else {
                ticketDao.updateTicket(ticket);
            }
        }
        return ticket;
    }

    @Override
    public Ticket updateTicket(Ticket ticket) throws AppBusinessException {

        return null;
    }

    @Override
    public Ticket getTicketById(String id) throws AppBusinessException {
        if (Common.empty(id))
            return null;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        List<Ticket> tlist = ticketDao.getTicket(map);
        if (tlist != null && tlist.size() > 0) {
            return tlist.get(0);
        }
        return null;
    }

    @Override
    public Ticket delTicket(String id) throws AppBusinessException {
        Ticket ticket = getTicketById(id);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        ticketDao.delTicket(map);
        return ticket;
    }

    @Override
    public List<TicketPrice> getTicketPrice(String ticketId) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ticketId", ticketId);
        return ticketDao.getTicketPrice(map);
    }

    @Override
    public List<TicketPrice> resPriceList(Ticket ticket) throws AppBusinessException {
        if (ticket == null)
            return null;
        List<TicketPrice> resPriceList = new ArrayList<TicketPrice>();

        List<TicketPrice> tpList = getTicketPrice(ticket.getId());
        int befores = ticket.getBefores();
        Date startDate = Common.addDate(new Date(), befores + 1);
        cal.setTime(startDate);
        int weekday = cal.get(Calendar.DAY_OF_WEEK);
        for (int i = 0; i < weekday - 1; i++) {
            Date prevDate = Common.addDate(startDate, -weekday + i + 1);
            TicketPrice tp = new TicketPrice();
            tp.setTicketId(ticket.getId());
            tp.setPriceComHas(ticket.getPriceComHas());
            tp.setSpDate(Common.getFormatDate(prevDate, "yyyy-MM-dd"));
            resPriceList.add(tp);
        }

        for (int i = 0; i < 43 - weekday; i++) {
            TicketPrice tp = new TicketPrice();
            Date spDate = Common.addDate(startDate, i);
            String tmpDate = Common.getFormatDate(spDate, "yyyy-MM-dd");
            tp.setTicketId(ticket.getId());
            tp.setSpDate(tmpDate);
            tp.setPriceA(ticket.getPriceComA());
            tp.setPriceC(ticket.getPriceComC());
            tp.setPriceComHas(ticket.getPriceComHas());
            for (TicketPrice ticketPrice : tpList) {
                String spDate1 = ticketPrice.getSpDate();
                if (tmpDate.equals(spDate1)) {
                    tp = ticketPrice;
                    tp.setPriceComHas(true);
                    break;
                }
            }
            resPriceList.add(tp);
        }

        cal.add(Calendar.MONTH, 1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        weekday = cal.get(Calendar.DAY_OF_WEEK);
        for (int i = 0; i < weekday - 1; i++) {
            Date prevDate = Common.addDate(cal.getTime(), -weekday + i + 1);
            String tmpDate = Common.getFormatDate(prevDate, "yyyy-MM-dd");
            TicketPrice tp = new TicketPrice();
            tp.setTicketId(ticket.getId());
            tp.setPriceA(ticket.getPriceComA());
            tp.setPriceC(ticket.getPriceComC());
            tp.setSpDate(tmpDate);
            tp.setPriceComHas(ticket.getPriceComHas());
            for (TicketPrice ticketPrice : tpList) {
                String spDate1 = ticketPrice.getSpDate();
                if (tmpDate.equals(spDate1)) {
                    tp = ticketPrice;
                    tp.setPriceComHas(true);
                    break;
                }
            }
            resPriceList.add(tp);
        }

        for (int i = 0; i < 43 - weekday; i++) {
            TicketPrice tp = new TicketPrice();
            Date spDate = Common.addDate(cal.getTime(), i);
            String tmpDate = Common.getFormatDate(spDate, "yyyy-MM-dd");
            tp.setTicketId(ticket.getId());
            tp.setSpDate(tmpDate);
            tp.setPriceA(ticket.getPriceComA());
            tp.setPriceC(ticket.getPriceComC());
            tp.setPriceComHas(ticket.getPriceComHas());
            for (TicketPrice ticketPrice : tpList) {
                String spDate1 = ticketPrice.getSpDate();
                if (tmpDate.equals(spDate1)) {
                    tp = ticketPrice;
                    tp.setPriceComHas(true);
                    break;
                }
            }
            resPriceList.add(tp);
        }

        return resPriceList;
    }

    @Override
    public void saveTicketPrice(String ticketId, String tpList) throws AppBusinessException {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();// 事务定义类
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);// 设置事务传播属性
        TransactionStatus status = transactionManager.getTransaction(def);// 返回事务对象
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("ticketId", ticketId);
            ticketDao.delTicketPrice(map);

            JSONArray list = JSONArray.fromObject(Encode.unescape(tpList));
            for (Object object : list) {
                TicketPrice tp = (TicketPrice) JSONObject.toBean((JSONObject) object, TicketPrice.class);
                ticketDao.insertTicketPrice(tp);
            }
            transactionManager.commit(status);// 提交事务
        } catch (Exception e) {
            transactionManager.rollback(status);// 回滚事务
            throw new AppBusinessException(e);
        }

    }

    @Override
    public TicketPrice getTodayPrice(Ticket ticket) throws AppBusinessException {
        if (ticket == null)
            return null;
        TicketPrice dayPrice = new TicketPrice();
        int befores = ticket.getBefores();
        Date startDate = Common.addDate(new Date(), befores + 1);
        String now = Common.getFormatDate(startDate, "yyyy-MM-dd");
        dayPrice.setPriceA(ticket.getPriceComA());
        dayPrice.setPriceC(ticket.getPriceComC());
        dayPrice.setSpDate(now);

        List<TicketPrice> tpList = getTicketPrice(ticket.getId());
        if (tpList != null && tpList.size() > 0) {
            for (TicketPrice ticketPrice : tpList) {
                String spDate = ticketPrice.getSpDate();
                if (now.equals(spDate)) {
                    dayPrice = ticketPrice;
                    break;
                }
            }
        }
        return getDayPrice(ticket, null);
    }

    @Override
    public TicketPrice getDayPrice(Ticket ticket, String date) throws AppBusinessException {
        if (ticket == null)
            return null;
        String now = null;
        TicketPrice dayPrice = new TicketPrice();
        int befores = ticket.getBefores();
        Date startDate = Common.addDate(new Date(), befores + 1);
        if (Common.empty(date)) {
            now = Common.getFormatDate(startDate, "yyyy-MM-dd");
        } else {
            now = date;
        }
        dayPrice.setPriceA(ticket.getPriceComA());
        dayPrice.setPriceC(ticket.getPriceComC());
        dayPrice.setSpDate(now);

        List<TicketPrice> tpList = getTicketPrice(ticket.getId());
        if (tpList != null && tpList.size() > 0) {
            for (TicketPrice ticketPrice : tpList) {
                String spDate = ticketPrice.getSpDate();
                if (now.equals(spDate)) {
                    dayPrice = ticketPrice;
                    break;
                }
            }
        }
        return dayPrice;
    }

    @Override
    public List<Ticket> getTicketByCompany(String company) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("company", company);
        List<Ticket> list = ticketDao.getTicket(map);
        return list;
    }

}
